package com.jzoom.caster.impl;

import com.jzoom.caster.Caster;
import com.jzoom.caster.ValueCaster;

public class JsonCasters {

	
	private static class String2Boolean implements ValueCaster {

		@Override
		public Object to(Object src) {
			return Boolean.parseBoolean( (String) src);
		}

	}

	private static class String2Integer implements ValueCaster {

		@Override
		public Object to(Object src) {
			String str = (String) src;
			if(str.contains(".")){
				return (int) (double) Double.parseDouble(str);
			}
			return Integer.parseInt( str);
		}

	}

	private static class String2Double implements ValueCaster {

		@Override
		public Object to(Object src) {
			return Double.parseDouble( (String) src);
		}

	}

	public static void init(){
		Caster.register(Number.class, Double.class, new JsonCasters.Number2Double());
		Caster.register(Number.class, Integer.class, new JsonCasters.Number2Integer());
		Caster.register(Number.class, Boolean.class, new JsonCasters.Number2Boolean());
		
		Caster.register(String.class, Double.class, new JsonCasters.String2Double());
		Caster.register(String.class, Integer.class, new JsonCasters.String2Integer());
		Caster.register(String.class, Boolean.class, new JsonCasters.String2Boolean());
		
		//json array
		
		Caster.register(String.class, double.class, new JsonCasters.String2Double());
		Caster.register(String.class, int.class, new JsonCasters.String2Integer());
		Caster.register(String.class, boolean.class, new JsonCasters.String2Boolean());
		
		
	}

	private static class Number2Integer implements ValueCaster {

		@Override
		public Object to(Object src) {
			return ((Number) src).intValue();
		}

	}
	
	private static class Number2Boolean implements ValueCaster {

		@Override
		public Object to(Object src) {
			return ((Number) src).intValue()==0?Boolean.FALSE:Boolean.TRUE;
		}

	}
	
	private static class Number2Double implements ValueCaster {

		@Override
		public Object to(Object src) {
			return ((Number) src).doubleValue();
		}

	}


}
